import 'dart:convert';

import 'package:flutter/material.dart';

extension MyJson on String {
  Map<String, dynamic> toMap() {
    Map<String, dynamic> map = json.decode(this);
    return map;
  }

  List toList() {
    List list = json.decode(this);
    return list;
  }

  dynamic toObj() {
    return json.decode(this);
  }

  bool isJson() {
    try {
      dynamic obj = json.decode(this);
      if (obj is Map) {
        return true;
      }
      if (obj is List) {
        return true;
      }
      return false;
    } catch (e) {
      return false;
    }
  }

  static bool isUrl(String? url) {
    if (url == null) {
      return false;
    }
    return RegExp(
            r"^(https?|ftp|file)://[-A-Za-z0-9+&amp;@#/%?=~_|!:,.;]+[-A-Za-z0-9+&amp;@#/%=~_|]$")
        .hasMatch(url);
  }

  static Size textSize(BuildContext context, String text,
      {required TextStyle textStyle}) {
    final textSpan = TextSpan(
      text: text,
      style: textStyle,
    );
    final textPainter = TextPainter(
        text: textSpan, textDirection: TextDirection.ltr, maxLines: 4)
      ..layout(
          maxWidth:
              MediaQuery.of(context).size.width - 30); // 减去/加上的数值根据自己需求调整，下同
    return textPainter.size;
  }
}

extension StringExtension on String {
  String capitalize() {
    if (trim().isEmpty) return '';
    return "${this[0].toUpperCase()}${substring(1)}";
  }
}
